# -*- coding: utf-8 -*-

# @Time   : 2021/12/14 5:13 下午
# @Author : 贾浩天
# @Email  : jiahaotian@rokedata.com
# @File   : roke_excel_import.py
# @Description: excel导入配置后台代码

from odoo import models, fields, api, _
from odoo.exceptions import UserError
from io import BytesIO
from collections import Counter

import logging
import xlwt
import base64

_logger = logging.getLogger(__name__)


class RokeExcelConfig(models.Model):
    _name = "roke.excel.import.config"
    _description = "导入配置"
    _rec_name = "model_id"

    model_id = fields.Many2one('ir.model', string='模型')
    field_ids = fields.One2many('roke.excel.import.config_field', 'model_id', string='模型字段')
    file = fields.Binary('文件')
    create_flag = fields.Boolean('保存状态', default=False)

    @api.model
    def create(self, vals):
        create_list = []
        res = super(RokeExcelConfig, self).create(vals)
        res.create_flag = True
        # 获取对象中的必填字段
        _required = self.env['ir.model.fields'].search([('model_id', '=', res.model_id.id), ('required', '=', True)])
        field_list = [field.field_id.id for field in res.field_ids]
        seq_list = [field.sequence for field in res.field_ids]
        # 排序取最后一个递增
        seq_list.sort(reverse=True)
        seq = 0
        if seq_list:
            seq = seq_list[0]
        for _req in _required:
            if _req.id not in field_list:
                seq += 1
                create_list.append({'model_id': res.id,
                                    'field_id': _req.id,
                                    'field_code': _req.name,
                                    'field_name': _req.field_description,
                                    'sequence': seq
                                    })
        self.env['roke.excel.import.config_field'].create(create_list)
        # 保存时校验数字是否重复
        for record in res.field_ids:
            seq_list = [obj.sequence for obj in record.model_id.field_ids]
            result = Counter(seq_list)
            for seq in result:
                if result[seq] > 1:
                    raise UserError('导入顺序不可相同！')
        return res

    def write(self, vals):
        res = super(RokeExcelConfig, self).write(vals)
        for record in self.field_ids:
            seq_list = [obj.sequence for obj in record.model_id.field_ids]
            result = Counter(seq_list)
            for seq in result:
                if result[seq] > 1:
                    raise UserError('导入顺序不可相同！')
        return res

    def button_import_data(self):

        return {
            'name': '导入数据',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'res_model': 'roke.excel.import.config.wizard',
            'context': {
                'default_model_id': self.id,
            }
        }

    def get_field_name(self):
        fields_list = []
        for record in self.field_ids:
            fields_list.append(record.field_id.field_description)
        return fields_list

    def generate_excel(self):
        result = [self.get_field_name()]
        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet(self.model_id.model, cell_overwrite_ok=True)
        for i in range(len(result)):
            for j in range(len(result[i])):
                sheet.write(i, j, result[i][j])
        buffer = BytesIO()
        wbk.save(buffer)
        data = base64.encodebytes(buffer.getvalue())
        return data

    def download_excel(self):
        model_name = "roke.excel.import.config"
        excel_name = self.model_id.name + "导入模板"
        self.file = self.generate_excel()
        url = '/web/content?model=%s&id=%s&field=file&download=true&filename=%s.xls'
        excel_url = url % (model_name,  self.id, excel_name)
        value = dict(
            type='ir.actions.act_url',
            target='self',
            url=excel_url
        )
        return value


class RokeExcelConfigField(models.Model):
    _name = "roke.excel.import.config_field"
    _description = "导入配置_字段"
    _order = "sequence"

    model_id = fields.Many2one('roke.excel.import.config', string='导入配置', ondelete='cascade')
    field_code = fields.Char(string='字段编码')
    field_name = fields.Char(string='字段描述')
    field_id = fields.Many2one('ir.model.fields', string="模型字段")
    field_type = fields.Selection(related='field_id.ttype', string="字段类型")
    default_flag = fields.Boolean(string='flag', default=True)
    sequence = fields.Integer('导入顺序', help='数字小的导入时在前。')
    not_id = fields.Boolean('不根据ID', default=False, help='勾选后不根据id导入，根据「导入字段」进行导入。')
    custom = fields.Char('导入字段', default=False, help='必须在本字段表中出现，且值唯一。')

    _sql_constraints = [
        ('field_uniq', 'unique (model_id, field_id)', '禁止选择相同字段！'),
    ]

    @api.onchange('model_id')
    def _onchange_model_id(self):
        domain_list = []
        fields = self.env['ir.model.fields'].search([('model_id', '=', self.model_id.model_id.id)])
        for field_obj in fields:
            domain_list.append(field_obj.id)
        domain = {'field_id': [('id', 'in', domain_list)]}
        return {'domain': domain}

    @api.onchange('field_id')
    def _onchange_field_id(self):
        field = self.field_id
        if self.field_id:
            self.field_code = field.name
            self.field_name = field.field_description
